package com.app.util.collection;

import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;

public class CollectionUtil {

	public static <T> void fillCollection(Collection<T> collection, T[] objs) {
		fillCollection(collection, objs, null);
	}

	public static <T> void fillCollection(Collection<T> collection, T[] objs, Filter<T> filter) {
		if (null == objs || null == collection) {
			return;
		}
		for (T t : objs) {
			if (null == filter || filter.accept(t)) {
				collection.add(t);
			}
		}
	} 

	public static <T> Collection<T>[] split(Collection<T> c, int limit) {
		int size = c.size();
		int arraySize = size % limit == 0 ? size / limit : size / limit + 1;
		Collection<T>[] arr = (Collection<T>[]) Array.newInstance(c.getClass(), arraySize);
		int index = 0;
		Iterator<T> it = c.iterator();
		for (int i = 0; i < arraySize; i++) {
			Collection<T> list;
			try {
				list = c.getClass().newInstance();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
			for (int j = 0; j < limit && index < size; j++) {
				list.add(it.next());
				index++;
			}
			arr[i] = list;
		}
		return arr;
	}

	public static interface Filter<T> {
		public boolean accept(T t);
	}
}
